import URI from 'urijs';
import { errorHandler } from './request';
import { notification } from 'antd';
import settings from '@/settings';

export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};

/**
 * ('无', '/地区/省/无锡市') => { name: '无锡市', names: '/地区/省/<strong>无</strong>锡市' }
 */
export const getQueryKeywords = (s, names) => {
  const re = new RegExp(s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1"), 'gi');

  const _names = names.split('/')
  const name = _names[_names.length - 1];
  _names[_names.length - 1] = name.replace(re, '<strong>' + s + '</strong>');

  return {
    name,
    names: _names.join("/")
  }
}

export const formatUrl = (url, params) => url.replace(/([^:\/])\/\/+/g, "$1\/").replace(/\/\/+([^:\/])/g, "\/$1").replace(/\/:([^\/]+)/g, function(s, name) {
    let value = ''
    if (params) {
      value = params[name]
      params[name] = null
      delete params[name]
    }
    return value ? ("/" + value) : ''
  })

const { pagination } = settings;

export const getData = (response = {}) => {
  const _data = {}
  if (typeof response !== 'object') {
    notification.error({
      message: '不正确的返回格式',
    });
    return _data;
  }
  const {
    code,
    data = _data
  } = response
  if (code !== settings.code) {
    errorHandler(response)
    return _data;
  }
  return data
}

/**
 * 公共参数（分页信息合并）
 */
export const formatParams = (params = {}) => {
  return {
    ...pagination,
    ...params,
  };
};

export const delay = time => new Promise(resolve => setTimeout(resolve, time))

export const createAction = type => payload => ({ type, payload })

export const isAdmin = user => {
  return user.userType === -1 && user.orgId === -1;
};

export const setType = async file => {
  const name = file.name;
  const n = name.lastIndexOf('.'),
    ext = name.substr(n + 1, name.length - 1).toLowerCase();
  if (['png', 'jpeg', 'jpg', 'gif', 'bmp'].indexOf(ext) >= 0) {
    // file.src = await getBase64(file.originFileObj);
    file.src = await getBase64(file);
  } else {
    const type = ["doc", "docx"].indexOf(ext) >= 0 ? "doc" : ["ppt", "pptx"].indexOf(ext) >= 0 ? "ppt" : ["xls", "xlsx"].indexOf(ext) >= 0 ? "xls" : "pdf" === ext ? "pdf" : "txt" === ext ? "txt" : "apk" === ext ? "apk" : "bak" === ext ? "bak" : "cs" === ext ? "cs" : "csv" === ext ? "csv" : "exe" === ext ? "exe" : "fla" === ext ? "fla" : "html" === ext ? "html" : "ipa" === ext ? "ipa" : "java" === ext ? "java" : "js" === ext ? "js" : "mp3" === ext ? "mp3" : "mp4" === ext ? "mp4" : "php" === ext ? "php" : "rar" === ext ? "rar" : "swf" === ext ? "swf" : "ttf" === ext ? "ttf" : "vss" === ext ? "vss" : "xsd" === ext ? "xsd" : "zip" === ext ? "zip" : "youdaonote" === ext ? "youdaonote" : "evernote" === ext ? "evernote" : "yinxiang" === ext ? "yinxiang" : "quip" === ext ? "quip" : "onenote" === ext ? "onenote" : "onedrive" === ext ? "onedrive" : "box" === ext ? "box" : "shimo" === ext ? "shimo" : "processon" === ext ? "processon" : "default";
    file.src = require(`../assets/images/type/${type}.png`);
  }
};

// const idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
// const numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
// export const numberFormat = (value) => {
//     value = value + '';
//     const len = value.length - 1;
//     return value.replace(/([1-9]|0+)/g, function($, $1, idx, full) {
//         let pos = 0;
//         if ($1[0] !== '0') {
//             pos = len - idx;
//             if (idx === 0 && $1[0] === 1 && idxs[len - idx] === '十') {
//                 return idxs[len - idx];
//             }
//             return numbers[$1[0]] + idxs[len - idx];
//         } else {
//             const left = len - idx;
//             const right = len - idx + $1.length;
//             if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
//                 pos = left - left % 4;
//             }
//             if (pos) {
//                 return idxs[pos] + numbers[$1[0]];
//             } else if (idx + $1.length >= len) {
//                 return '';
//             } else {
//                 return numbers[$1[0]]
//             }
//         }
//     });
// }

// export const download = (blob, fileName) => {
//     if (window.navigator.msSaveOrOpenBlob) {
//         navigator.msSaveBlob(blob, fileName);
//     } else {
//         var link = document.createElement('a');
//         var href = window.URL.createObjectURL(blob);
//         link.href = href;
//         link.download = fileName;
//         document.body.appendChild(link);
//         var evt = document.createEvent("MouseEvents");
//         evt.initEvent("click", false, false);
//         link.dispatchEvent(evt);
//         document.body.removeChild(link);
//         window.URL.revokeObjectURL(href);
//     }
// }

const uid = '__download';

export const download = (url, params) => {
  var iframe = document.getElementById(uid);
  if (!iframe) {
    iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.setAttribute('id', uid);
    document.body.appendChild(iframe);
  }

  var uri = new URI(url);
  url = uri
    .search({
      ...uri.search(true),
      ...params,
      temp: new Date().getTime(),
    })
    .normalize()
    .toString();

  iframe.src = `${settings.base}/${url}`;
};

export const toBytes = bytes => {
  bytes = parseInt(bytes, 10);
  if (isNaN(bytes)) return '';
  if (bytes === 0) return '0 B';

  const k = 1024;

  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  if (i > sizes.length - 1) {
    return 'max';
  }

  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
};

export const mapping = (value, object) => {
  if (value == null) return value;
  if (Array.isArray(object)) {
    var _item = object.filter(function (item) {
      var val = item.id == null ? item.value : item.id;
      return val != null && val.toString() === value.toString();
    })[0];
    return _item ? _item.name || _item.value : value;
  } else {
    return object[value] || value;
  }
};